<?php
/**
 * Created by PhpStorm.
 * User: hongy
 * Date: 2016/1/27
 * Time: 17:41
 */

namespace Common\Common;

//获取用户access_token(网页授权)
define('WX_API_token',"https://api.weixin.qq.com/sns/oauth2/access_token");
//获取用户access_token
define('WX_API_access_token',"https://api.weixin.qq.com/cgi-bin/token");
//获取用户信息
define('WX_API_INFO',"https://api.weixin.qq.com/cgi-bin/user/info");
//判断access_token是否有效
define('WX_API_check',"https://api.weixin.qq.com/sns/auth");
define('WX_API_refresh',"https://api.weixin.qq.com/sns/oauth2/refresh_token");


define ('appid',"wx2e1ad7100fd503cc");
define('secret',"229ba4a5bdabd7605d4c2f248a60b994");
class wechat
{

    public static function getAccessToken($code){

        $para = array(

            "appid" => appid,
            "secret" => secret,
            "code" => $code,
            "grant_type" => "authorization_code"
        );
        //获取用户access_token

        $ret = wechat::doCurlGetRequest(WX_API_token,$para);
        $t = json_decode($ret);
        return $t;
    }

    public static function refreshToken($refresh_token){
        $para = array(

            "appid" => appid,
            "grant_type" => 'refresh_token',
            "refresh_token"=>$refresh_token
        );
        $ret = wechat::doCurlGetRequest(WX_API_refresh,$para);
        $t = json_decode($ret);
        return $t;
    }

    public static function getToken(){
        $para = array(
            "grant_type" => "client_credential",
            "appid" => appid,
            "secret" => secret
        );
        $ret = wechat::doCurlGetRequest(WX_API_access_token,$para);
        $t = json_decode($ret);
        return $t;
    }

    public static function getInfo($openid){
        $access_token = wechat::getToken()->access_token;
        $para = array(
            'access_token' => $access_token,
            'openid'    =>  $openid,
            'lang'  =>  'zh_CN'
        );
        $ret = wechat::doCurlGetRequest(WX_API_INFO,$para);
        $t = json_decode($ret);
        return $t;
    }

    public static function checkToken($openid,$access_token){
        $para = array(
            'access_token'=>$access_token,
            'openid'    =>  $openid
        );
        $ret = wechat::doCurlGetRequest(WX_API_check,$para);
        $t=json_decode($ret);
        return $t;
    }
    public function doCurlGetRequest($url,$data,$timeout = 5){
        if($url == "" || $timeout <=0){
            return false;
        }
        $url = $url . '?' . http_build_query($data);

        $con = curl_init((string)$url);
        curl_setopt($con,CURLOPT_HEADER,false);
        curl_setopt($con,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($con,CURLOPT_TIMEOUT,(int)$timeout);
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($con);
        // 检查是否有错误发生
        if( curl_errno ( $con )) {
            echo  'Curl 1 error: '  .  curl_error ( $con );
        }
        return $result;
    }
}